<?php
// api/save_progress.php
header('Content-Type: application/json');
require 'db.php';

// Get JSON input
$input = json_decode(file_get_contents('php://input'), true);

if (!$input) {
    echo json_encode(['success' => false, 'message' => 'No data received']);
    exit;
}

$user_name = $input['user_name'] ?? 'guest';
$app_id = $input['app_id'] ?? 'unknown';
$question_id = $input['question_id'] ?? '';
$is_correct = $input['is_correct'] ? 1 : 0;

if (!$question_id) {
    echo json_encode(['success' => false, 'message' => 'Missing question_id']);
    exit;
}

try {
    // Optional: Check if already answered correctly to avoid duplicates? 
    // For now, let's just log every attempt or maybe just update?
    // User asked to "registrar progresso" (register progress). Simple log is safest.
    
    $stmt = $pdo->prepare("INSERT INTO user_progress (user_name, app_id, question_id, is_correct, timestamp) VALUES (?, ?, ?, ?, CURRENT_TIMESTAMP)");
    $stmt->execute([$user_name, $app_id, $question_id, $is_correct]);
    
    echo json_encode(['success' => true]);

} catch (PDOException $e) {
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>
